const mysql = require("mysql");
const config = require("./config/config.json");
const classPool = require("./ClassPool.json");
const { logger } = require("./logger.js");

// const CryptoJS = require("crypto-js")
const db = mysql.createPool(config.mysql);

const Handler = require("./handler.js");


//=====================================================================
//登录
exports.logon = (req, res) => {
    const { user, password } = req.body;
    const sql = `select * from user where user=?`;
    const ip = ((req.headers['x-forwarded-for'] || '').split(',')[0] || req.ip).replace(/"ffff"/g, 'ip');
    db.query(sql, [user], (err, result) => {
        if (err) {
            res.send({ "code": 99 });
            throw err;
        }
        if (result.length === 0) {
            res.send({ "code": 102 });
            return;
        }
        if (result[0].password === password) {
            const token = Handler.userToToken(user);
            res.send({ "code": 100, "token": token });
            logger.info(`用户${user}通过${ip}登录...`);
        } else {
            res.send({ "code": 103 });
        }
    })
}

//注册
exports.register = (req, res) => {
    const { user, password } = req.body;
    const sql = "SELECT user FROM user WHERE user=?";
    const sql2 = "INSERT INTO user(user, password) values(?, ?)";
    const ip = ((req.headers['x-forwarded-for'] || '').split(',')[0] || req.ip).replace(/"ffff"/g, 'ip');
    db.query(sql, [user], (err, result) => {
        if (err) {
            res.send({ "code": 99 });
            throw err;
        }
        if (result.length === 0) {
            db.query(sql2, [user, password], (err, result) => {
                if (err) {
                    res.send({ "code": 99 });
                    throw err;
                }
                res.send({ "code": 100 });
                logger.info(`${ip}注册用户"${user}"成功...`);
            })
        } else {
            res.send({ "code": 101 });
        }
    })
}

//角色列表
exports.actor = (req, res) => {
    const { token } = req.body;
    const user = Handler.tokenToUser(token)[0];
    //测试数据
    const sql = "SELECT name, class_id, level, character_name, character_index, uid FROM actor WHERE user = ?";
    db.query(sql, [user], (err, result) => {
        if (err) {
            res.send({ "code": 99 });
            throw err;
        }
        res.send({ "code": 100, "actor": result });
    })
}

//创建角色
exports.creatActor = (req, res) => {
    const { token, name, id } = req.body;
    const { position } = config.game;
    const { classId, characterName, characterIndex, faceName, faceIndex, className } = classPool[id];
    const sql = "SELECT name FROM actor WHERE name = ?";
    const sql2 = "INSERT INTO actor(user, name, class_id, character_name, character_index, face_name, face_index, map_id, map_x, map_y) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    // const sql3 = "INSERT INTO actorData(name, battlerName, classId) values(?, ?, ?)";
    const user = Handler.tokenToUser(token)[0];
    db.query(sql, [name], (err, result) => {
        if (err) {
            res.send({ "code": 99 });
            throw err;
        }
        if (result.length === 0) {
            db.query(sql2, [user, name, classId, characterName, characterIndex, faceName, faceIndex, position[0], position[1], position[2]], (err, result) => {
                if (err) {
                    res.send({ "code": 99 });
                    throw err;
                }
                res.send({ "code": 100 });
                logger.info(`用户${user}创建了${className}角色${name}...`);
                // db.query(sql3, [name, battlerName, id], (err, result) => {
                //     if (err) {
                //         res.send({ "code": 99 });
                //         throw err;
                //     }
                //     res.send({ "code": 100 });
                // })
            })
        } else {
            res.send({ "code": 104 });
        }
    })
}

//鉴权
exports.authentication = (req, res) => {
    const { uid, token } = req.body;
    const user = Handler.tokenToUser(token)[0];
    const sql = "SELECT user FROM actor WHERE uid = ?";
    const identity = Handler.getIdentityId(uid);

    db.query(sql, [uid], (err, result) => {
        if (err) {
            res.send({ "code": 99 });
            throw err;
        }
        if (result[0].user === user) {
            res.send({ "code": 100, "identity": identity });
        }
    })
}


//======================================================================
//==============================地图服务器===============================
//======================================================================

//获取角色信息
exports.getActorInfo = (uid, socket, call_back) => {
    const sql = "SELECT * FROM actor WHERE uid=?";
    db.query(sql, [uid], (err, result) => {
        if (err) throw err;
        if (result[0]) {
            call_back(result[0], socket);
        }
    })
}

exports.updatePosition = (uid, data) => {
    const { mapId, x, y } = data;
    const sql = "UPDATE actor SET map_id = ?, map_x = ?, map_y = ? WHERE uid = ?";
    db.query(sql, [mapId, x, y, uid], (err, result) => {
        if (err) throw err;
    })
}

exports.getActorBattleInfo = (data, call_back) => {
    const { partyRoom, battleMember, battleData } = data;
    let sql = "SELECT * FROM actor_data WHERE ";
    const arr = [];
    if (battleMember[0]) {
        sql += `name = ?`;
        arr.push(battleMember[0]);
    }
    if (battleMember[1]) {
        sql += ` OR name = ?`;
        arr.push(battleMember[1]);
    }
    if (battleMember[2]) {
        sql += ` OR name = ?`;
        arr.push(battleMember[2]);
    }
    if (battleMember[3]) {
        sql += ` OR name = ?`;
        arr.push(battleMember[3]);
    }
    if (battleMember[4]) {
        sql += ` OR name = ?`;
        arr.push(battleMember[4]);
    }
    db.query(sql, arr, (err, result) => {
        if (err) throw err;
        call_back(result, partyRoom, battleData)
    })
}

//======================================================================
//==============================数据服务器===============================
//======================================================================
exports.getActorData = (name, socket, call_back) => {
    const sql = "SELECT * FROM actor_data WHERE name=?";
    db.query(sql, [name], (err, result) => {
        if (err) throw err;
        if (result[0]) {
            call_back(result[0], socket);
        }
    })
}

//更新经验值
exports.updateExp = (name, data) => {
    const { exp, level } = data;
    const sql = "UPDATE actor_data SET exp = ?,level = ? WHERE name = ?";
    db.query(sql, [exp, level, name], (err, result) => {
        if (err) throw err;
    })
}